package cn.devcat.sso.service.impl;

import cn.devcat.sso.entity.NoteTag;
import cn.devcat.sso.entity.PageData;
import cn.devcat.sso.entity.SearchCommonParam;
import cn.devcat.sso.mapper.NoteTagMapper;
import cn.devcat.sso.service.INoteTagService;
import cn.devcat.sso.util.PageHelperUtil;
import cn.devcat.sso.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NoteTagServiceImpl extends ServiceImpl<NoteTagMapper, NoteTag> implements INoteTagService {

  @Resource
  NoteTagMapper noteTagMapper;

  @Autowired
  UserUtil userUtil;

  @Override
  public void addTag(NoteTag noteTag) {
    String userId = userUtil.getUserByRequest().getId();
    noteTag.setUserId(userId);
    noteTag.setCreateTime(LocalDateTime.now());
    noteTag.setQuoteCount(1);
    long count = count(new QueryWrapper<NoteTag>().eq("tag_name", noteTag.getTagName()));
    if (count > 0) {
      throw new RuntimeException("标签名重复");
    }
    save(noteTag);
  }

  @Override
  public void delTag(List<Long> ids) {
    for (Long id : ids) {
      noteTagMapper.unbindRelation(id, "tag");
    }
    removeByIds(ids);
  }

  @Override
  public void setTag(NoteTag noteTag) {
    long count = count(new QueryWrapper<NoteTag>().ne("id", noteTag.getId()).eq("tag_name", noteTag.getTagName()));
    if (count > 0) {
      throw new RuntimeException("存在相同名称标签");
    }
    updateById(noteTag);
  }

  @Override
  public PageData<NoteTag> tagList(SearchCommonParam param) {
    PageHelperUtil.handle(param);
    List<NoteTag> noteTagList = noteTagMapper.getNoteTagList(param);
    return PageHelperUtil.makePageData(new PageInfo<>(noteTagList));
  }

  @Override
  public void bindTagRelation(Long noteId, List<NoteTag> tagList) {
    List<Long> collect = tagList.stream().map(NoteTag::getId).collect(Collectors.toList());
    noteTagMapper.bindTagRelation(noteId, collect);
  }

  @Override
  public void unbindTagRelation(List<Long> ids, String type) {
    for (Long id : ids) {
      noteTagMapper.unbindRelation(id, type);
    }
  }

  @Override
  public List<NoteTag> getTagListByNoteId(Long noteId) {
    SearchCommonParam param = new SearchCommonParam();
    param.setNoteId(noteId);
    return noteTagMapper.getNoteTagList(param);
  }
}
